package com.example.moshudriver.fragment;

import java.util.Set;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.sgr.dykdriver.R;
import com.example.moshudriver.activity.SlidingActivity;
import com.example.moshudriver.jpush.ExampleUtil;
import com.example.moshudriver.tools.O2OMobileAppConst;
import com.external.maxwin.view.IXListViewListener;
import com.external.maxwin.view.XListView;

public class A0_HomeFragment extends Fragment implements OnClickListener,
		IXListViewListener {
	private ImageView mMenu, A0_back;
//	private ImageView  A0_bar_bell;
	// private LinearLayout A0_linearLayout_bottom;
	private View view;
	private TextView a0_order, a0_text_test;
	public static boolean isForeground = false;// 是否在后台
	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";
	private MessageReceiver mMessageReceiver;
	private TextView tv_listen_order;
	private XListView A0_orderlist;
	private     SharedPreferences mShared;
    private     SharedPreferences.Editor mEditor;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.a1_home, null);
		JPushInterface.init(getActivity());
		view.setOnClickListener(null);
		registerMessageReceiver();
		initView();
		mShared = getActivity().getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
        mEditor = mShared.edit();
        System.out.println("是否绑定："+mShared.getBoolean("isjpush", false));
        if (!mShared.getBoolean("isjpush", false)) {
        	
        	
            int uid = mShared.getInt("uid", 0);
            System.out.println("是否绑定："+uid);
    		setAlias(String.valueOf(uid));//绑定用户id到极光的服务器上（设置别名）
		}

		return view;
	}

	private void initView() {
		// a0_text_test=(TextView)view.findViewById(R.id.a0_text_test);
		// A0_linearLayout_bottom = (LinearLayout) view
		// .findViewById(R.id.A0_linearlayout_bottom);
		
//		A0_bar_bell = (ImageView) view.findViewById(R.id.A0_bar_bell);
		mMenu = (ImageView) view.findViewById(R.id.home_menu);
		A0_back = (ImageView) view.findViewById(R.id.A0_back);

		A0_orderlist = (XListView) view.findViewById(R.id.lv_a0_orderlist);
		A0_orderlist.setXListViewListener(this, 0);
		A0_orderlist.setPullLoadEnable(true);
		A0_orderlist.setRefreshTime();
		// 模拟加载数据，具体数据要从服务器获取
		OrderAdapter adapter = new OrderAdapter();
		A0_orderlist.setAdapter(adapter);
		A0_orderlist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 显示订单信息
				showDialog();
			}
		});

		mMenu.setOnClickListener(this);
//		A0_bar_bell.setOnClickListener(this);
		A0_back.setOnClickListener(this);

		// tv_listen_order = (TextView) view.findViewById(R.id.tv_listen_order);
		// tv_listen_order.setOnClickListener(this);
	}

	int count = 3;
	private Dialog dialog;

	class OrderAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return count;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = LayoutInflater.from(getActivity()).inflate(
					R.layout.show_order_list, null);
			TextView tv_start_place = (TextView) view
					.findViewById(R.id.tv_start_place);
			TextView tv_end_place = (TextView) view
					.findViewById(R.id.tv_end_place);
			TextView A0_distance = (TextView) view
					.findViewById(R.id.tv_a0_distance);
			TextView A0_price = (TextView) view.findViewById(R.id.tv_a0_price);

			return view;
		}

	}

	private void showConfirm() {
		mMenu.setVisibility(View.GONE);
		A0_back.setVisibility(View.VISIBLE);
//		A0_bar_bell.setVisibility(View.GONE);
		// A0_linearLayout_bottom.setVisibility(View.GONE);

	}

	private void hideConfirm() {
		mMenu.setVisibility(View.VISIBLE);
		A0_back.setVisibility(View.GONE);
//		A0_bar_bell.setVisibility(View.VISIBLE);
		// A0_linearLayout_bottom.setVisibility(View.VISIBLE);
	}

	@Override
	public void onDestroy() {
		getActivity().unregisterReceiver(mMessageReceiver);
		super.onDestroy();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();

	}

	@Override
	public void onPause() {
		isForeground = false;
		super.onPause();
	}

	@Override
	public void onResume() {
		isForeground = true;
		super.onResume();

	}

	// 注册监听
	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		getActivity().registerReceiver(mMessageReceiver, filter);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			System.out.println("广播收到自定义消息");

			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {

				String messge = intent.getStringExtra(KEY_MESSAGE);
				String extras = intent.getStringExtra(KEY_EXTRAS);
				StringBuilder showMsg = new StringBuilder();
				showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
				if (!ExampleUtil.isEmpty(extras)) {
					showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
				}
				Toast.makeText(getActivity(), showMsg.toString(), 2000).show();
//				Log.i("jpull,order_id", showMsg.append("order_id").toString());
				Log.i("jpull,order_id", messge.substring(messge.indexOf("order_id")));
				//获取到了订单id
				String mOrderId = messge.substring(messge.indexOf("order_id"));
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.home_menu:
			((SlidingActivity) getActivity()).showLeft();
			break;
		case R.id.A0_back:
			hideConfirm();
			break;
		// case R.id.tv_listen_order:
		// showDialog();
		// break;

		default:
			break;
		}
	}

	private void showDialog() {
		dialog = new Dialog(getActivity());
		// dialog去掉标题
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(loadView());
		dialog.setCancelable(true);
		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
//		lp.x = view.set; // 新位置X坐标
//		lp.y = view.getHeight()/2; // 新位置Y坐标
//		lp.width = view.getWidth()/2; // 宽度
//		lp.height = view.getHeight()/2; // 高度
		lp.alpha = 1.0f; // 透明度alpha在0.0f到1.0f之间。1.0完全不透明，0.0f完全透明

		dialogWindow.setAttributes(lp);

		dialog.show();
	}

	private View loadView() {
		LayoutInflater inflater = LayoutInflater.from(getActivity());
		view = inflater.inflate(R.layout.show_order_cell, null);
		Button btn_accept_order = (Button) view
				.findViewById(R.id.btn_accept_order);
		btn_accept_order.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(getActivity(), "您抢单了", 0).show();
				dialog.dismiss();

			}
		});
		return view;
	}

	@Override
	public void onRefresh(int id) {
		// TODO Auto-generated method stub
		// 请求订单列表，如
		// mMessageListModel.getList();
		count = 3;
	}

	@Override
	public void onLoadMore(int id) {
		// 请求加载更多订单列表，如
		// mMessageListModel.getListMore();
		count++;
	}
	
	// 极光推送设置别名
	private static final int MSG_SET_ALIAS = 1001;
	private void setAlias(String alias) {
		if (TextUtils.isEmpty(alias)) {
			return;
		}
		if (!ExampleUtil.isValidTagAndAlias(alias)) {

			return;
		}
		mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
	}
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case MSG_SET_ALIAS:
				JPushInterface.setAliasAndTags(getActivity(), (String) msg.obj,
						null, mAliasCallback);
				break;
			default:
			}
		}
	};
	private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

		@Override
		public void gotResult(int code, String alias, Set<String> tags) {
			String logs;
			switch (code) {
			case 0:
				mEditor.putBoolean("isjpush", true);
				mEditor.commit();
				System.out.println("极光推送绑定成功");
				break;

			case 6002:
				logs = "Failed to set alias and tags due to timeout. Try again after 6s.";
				System.out.println("logs" + logs);
				if (ExampleUtil.isConnected(getActivity())) {
					mHandler.sendMessageDelayed(
							mHandler.obtainMessage(MSG_SET_ALIAS, alias),
							1000 * 6);
				} else {
				}
				break;

			default:
				logs = "Failed with errorCode = " + code;

			}

		}
	};
}
